package com.mamingchao.concurrent.cas;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by mamingchao on 2020/7/8.
 */
public class CyclicBarrierTest {
    static AtomicInteger count = new AtomicInteger();
    static CyclicBarrier barrier = new CyclicBarrier(5, new Runnable() {
        @Override
        public void run() {
            System.out.println(count);
        }
    });

    public static void main(String[] args) {
        ExecutorService pool = Executors.newFixedThreadPool(10);

        for (int j=0;j<20;j++) {
            pool.execute(() -> {
                try {
                    barrier.await();
                    for (int i=0; i< 100;i++) {
                        count.incrementAndGet();
                    }

                }catch (InterruptedException e) {
                    e.printStackTrace();
                }catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            });
        }
    }
}
